//
//  HJRefreshControl.swift
//  WeiBo
//
//  Created by 韩俊 on 15/12/14.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import UIKit

private let RefreshControlH: CGFloat = 50

enum HJRefreshControlState:Int{
    
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class HJRefreshControl: UIControl {
    
    var oldHJState : HJRefreshControlState = .Normal
    
    var HJstate: HJRefreshControlState = .Normal {
        
        didSet{
            
            switch HJstate{
                
            case .Pulling :
                
                messageLabel.text = "释放刷新"
                
                UIView.animateWithDuration( 0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Normal :

                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicator.stopAnimating()
                
                UIView.animateWithDuration( 0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                
                if oldHJState == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= RefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
                
            case .Refreshing :
                
                messageLabel.text = "加载中"
                
                arrowIcon.hidden = true
                indicator.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top += RefreshControlH
                    self.scrollView?.contentInset = contentInset
                })
                
                sendActionsForControlEvents(.ValueChanged)
                
            }
            
            oldHJState = HJstate
        }
    }
    
    
    var scrollView : UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing(){
        
            HJstate = .Normal
       
    }
    
    
    private func setupUI(){
        backgroundColor = randomColor()
        
        var frame = self.frame
        frame.size = CGSizeMake(SCREENW, RefreshControlH)
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        //添加控件
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicator)

        //添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }

    }
    
    //当前控件将要添加到某个控件上的时候会调用
    override func willMoveToSuperview(newSuperview: UIView?) {
    
        //判断能不能滚动
        if let scrollView = newSuperview as? UIScrollView {
            //利用KVO 监听 newSuperView 的滚动
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
            
            self.scrollView = scrollView
            
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            self.frame = frame
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
       
        let contentOffsetY = scrollView?.contentOffset.y
        
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        
        let condintionValue = -contentInsetTop - RefreshControlH
        
        if scrollView!.dragging {
            
            if HJstate == .Normal && contentOffsetY < condintionValue {
                
                HJstate = .Pulling
                
            }else if HJstate == .Pulling && contentOffsetY >= condintionValue {
                
                HJstate = .Normal
            }
            
        }else{
            
            if HJstate == .Pulling {
                HJstate = .Refreshing
            }
        }
    }
    
    // MARK: - 懒加载
    
    //上下箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字
    private lazy var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    //菊花转
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    deinit {
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
